package com.jp.knowledge.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.TextView;

import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.command.CommandInvoker;
import com.jp.knowledge.command.CommandReceiver;
import com.jp.knowledge.command.implement.GangWeiZhiShiPaiXu;
import com.jp.knowledge.dialog.FirstLoginDialog;
import com.jp.knowledge.logic.PersonLogic;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.activity.UserSettingActivity;
import com.jp.knowledge.wxapi.WXEntryActivity;
import com.taobao.accs.base.BaseReceiver;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.modelbase.BaseResp;

import org.xutils.view.annotation.ViewInject;

import static com.jp.knowledge.wxapi.WXEntryActivity.WECHAT_BIND;

/**
 * 登录activity
 */
public class LoginActivity extends SlidingActivity implements View.OnClickListener {

    public static final String WEICHAT_LOGIN_STATE = "weiChatLoginState";

    @ViewInject(R.id.wechat_login)
    private TextView  wechatLogin;
    @ViewInject(R.id.phone_login)
    private TextView  phoneLogin;

    private IWXAPI api;
    private BroadcastReceiver broadcastReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @Override
    protected int getResourceId() {
        return R.layout.activity_login_select_acitivity;
    }

    @Override
    protected void init() {
        topName.setText("登录");
        rightIcon.setVisibility(View.GONE);
        leftIcon.setVisibility(View.VISIBLE);
        leftIcon.setImageResource(R.mipmap.guanzhufanhui);
        leftIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        application.putLoginActivity(this);
        wechatLogin.setOnClickListener(this);
        phoneLogin.setOnClickListener(this);
        api = WXAPIFactory.createWXAPI(mContext, JpApplication.weixin_appid,true);
        api.registerApp(JpApplication.weixin_appid);

        initBroadcast();
    }

    private void initBroadcast(){
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int errCode = intent.getIntExtra(WXEntryActivity.WECHAT_BIND_ERR_CODE, -1);
                if(errCode == BaseResp.ErrCode.ERR_OK){
                    String code = intent.getStringExtra(WXEntryActivity.WECHAT_BIND_RESULT_CODE);
                    if(code == null) {
                        ToasUtil.toast(mContext, "抱歉，认证出错，请稍后重试");
                        loading.cancel();
                    } else{
                        new PersonLogic(mContext, new PersonLogic.UserDataCallBack() {
                            @Override
                            public void done(UserData userData) {
                                loading.cancel();
                                if(userData == null)
                                    return;
                                sendLoginSuccessBroad();
                                application.closeLoginActivity();
                            }
                        }).getUserData(code);
                    }
                } else{
                    loading.cancel();
                }
            }
        };
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadcastManager.registerReceiver(broadcastReceiver, new IntentFilter(WECHAT_BIND));
    }

    @Override
    protected void onDestroy() {
        localBroadcastManager.unregisterReceiver(broadcastReceiver);
        super.onDestroy();
    }

    private void sendLoginSuccessBroad() {
        Intent intent =  new Intent(LocalBroadCast.LOGIN_SUCCESS_BROD);
        localBroadcastManager.sendBroadcast(intent);

        SharedPreferences sp = getSharedPreferences("loginMessage", MODE_PRIVATE);
        if(!sp.getBoolean("hadLogin", false)) {
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("hadLogin", true);
            editor.apply();
            // 首次登录
//            CommandInvoker.executeCommand(new GangWeiZhiShiPaiXu(new CommandReceiver(mContext)));
//            localBroadcastManager.sendBroadcast(new Intent(LocalBroadCast.FIRST_LOGIN));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.wechat_login:
                wechatLogin();
                break;
            case R.id.phone_login:
                startActivity(new Intent(mContext,LoginSelectAcitivity.class));
                break;
            default:
                break;
        }
    }

    /***
     * 微信登录
     */
    private void wechatLogin(){
//        SendAuth.Req req = new SendAuth.Req();
//        req.scope = "snsapi_userinfo";
//        req.state = "wechat_sdk_demo_test";

        if (!api.isWXAppInstalled()){
            ToasUtil.toast(this, "抱歉，你还未安装微信，请先安装后重试");
        } else {
            loading.show();
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = WEICHAT_LOGIN_STATE;
            api.sendReq(req);
        }
    }
}
